import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { Modal, notification } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import signMd5Utils from '@/utils/encryption/signMd5Utils'
import { VueAxios } from './axios'

/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
const apiBaseUrl = window._CONFIG['domianURL'] || '/jeecg-boot'
// 创建 axios 实例
const service = axios.create({
  baseURL: apiBaseUrl,
  timeout: 30000 // 请求超时时间
})
const requestList = new Set() // 定义存储请求url的对象参数
const debounceLimitedTime = 300 // 节流限制时间参数，默认为300ms
const notDebounceApiWhiteList = [
  '/sys/duplicate/check'
] // 不限制节流接口白名单
const err = (error) => {
  if (!axios.isCancel(error) && error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    switch (error.response.status) {
      case 403:
        notification.error({
          message: '系统提示',
          description: '拒绝访问',
          duration: 4
        })
        break
      case 500:
        const type = error.response.request.responseType
        if (type === 'blob') {
          blobToJson(data)
          break
        }
        if (token && data.message.includes('Token失效')) {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                try {
                  const path = window.document.location.pathname
                  if (path !== '/' && path.indexOf('/user/login') === -1) {
                    window.location.reload()
                  }
                } catch (e) {
                  window.location.reload()
                }
              })
            }
          })
        }
        break
      case 404:
        notification.error({
          message: '系统提示',
          description: '很抱歉，资源未找到!',
          duration: 4
        })
        break
      case 504:
        notification.error({
          message: '系统提示',
          description: '网络超时'
        })
        break
      case 401:
        notification.error({
          message: '系统提示',
          description: '未授权，请重新登录',
          duration: 4
        })
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
    requestList.delete(error.config.url) // 请求失败时，请求列表中移除请求url
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  // 不在不限制节流接口白名单中的接口，进行节流处理
  if (!notDebounceApiWhiteList.includes(config.url)) {
    // 利用cancelToken，取消当次请求
    config.cancelToken = new axios.CancelToken(e => {
      // 拦截重复请求
      let fullRequestUrl = apiBaseUrl + config.url
      if (config.url.split('/')[0].index !== 0) fullRequestUrl = `${apiBaseUrl}/${config.url}`
      requestList.has(`${apiBaseUrl}${config.url}`) ? e(`${config.url}:短时重复请求取消`) : requestList.add(fullRequestUrl)
    })
  }
  const tempArr = config.url.split(config.baseURL)
  const url = tempArr.length > 1 ? tempArr[1] : tempArr[0]
  const parameter = config.method === 'get' ? config.params : config.data
  const sign = signMd5Utils.getSign(url, parameter)
  config.headers['X-Sign'] = sign
  config.headers['X-TIMESTAMP'] = signMd5Utils.getDateTimeToString()
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  let tenantid = Vue.ls.get(TENANT_ID)
  if (!tenantid) {
    tenantid = 0
  }
  config.headers['tenant_id'] = tenantid
  if (config.method === 'get') {
    if (config.url.indexOf('sys/dict/getDictItems') < 0) {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
  // 设定定时事件(自定义时间)，移除当前请求url，防止请求被继续拦截
  setTimeout(() => {
    requestList.delete(response.config.url)
  }, debounceLimitedTime)
  // token失效拦截
  if (response.data.code === 510) {
    Modal.error({
      title: '登录已过期',
      content: '很抱歉，登录已过期，请重新登录',
      okText: '重新登录',
      mask: false,
      onOk: () => {
        store.dispatch('Logout').then(() => {
          Vue.ls.remove(ACCESS_TOKEN)
          window.location.reload()
        })
      }
    })
    return
  }
  return response.data
}, err)

// Blob解析
function blobToJson(data) {
  const fileReader = new FileReader()
  const token = Vue.ls.get(ACCESS_TOKEN)
  fileReader.onload = function() {
    try {
      const jsonData = JSON.parse(this.result) // 说明是普通对象数据，后台转换失败
      if (jsonData.status === 500) {
        if (token && jsonData.message.includes('Token失效')) {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                window.location.reload()
              })
            }
          })
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
    }
  }
  fileReader.readAsText(data)
}

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
